package ee.serge.server;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

import ee.serge.server.template.CalculatorTemplate;
import ee.serge.server.template.ChoosingALenderTemplate;
import ee.serge.server.template.ContactTemplate;
import ee.serge.server.template.FullLoansTemplate;
import ee.serge.server.template.KnowYourRightsTemplate;
import ee.serge.server.template.LoanDetailsTemplate;
import ee.serge.server.template.Template;


public final class CrawlFilter implements Filter {
   
   @Override
   public void init(FilterConfig arg0) throws ServletException {
   }

   @Override
   public void destroy() {
   }

   @Override
   public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
      //204
      
      HttpServletRequest r = (HttpServletRequest) request;
      String query = r.getQueryString();
      if (r.getRequestURI().contains("RecaptchaTest.nocache.js")) return;
      
      if (query == null || !query.contains("_escaped_fragment_=")) {
          chain.doFilter(request, response);
      } else {
         ServletOutputStream out = response.getOutputStream();
         String q = query.substring(query.indexOf("_escaped_fragment_=") + "_escaped_fragment_=".length());
         String template = null;
         try {
            template = handleQuery(q);
         } catch (Exception e) {
            e.printStackTrace();
            template = "404";
         }
         out.print(template);
      }
  }
   
   private String handleQuery(String query) throws Exception {
      Template template = null;
      if (query.contains("calculator") || query.length() == 0) {
         template = new CalculatorTemplate(query);
      } else if (query.contains("all_loans")) {
         template = new FullLoansTemplate(query);
      } else if (query.contains("loan")) {
         template = new LoanDetailsTemplate(query);
      } else if (query.contains("choosing_a_lender")) {
         template = new ChoosingALenderTemplate(query);
      } else if (query.contains("contact")) {
         template = new ContactTemplate(query);
      } else if (query.contains("know_your_rights")) {
         template = new KnowYourRightsTemplate(query);
      }
      return template.getTemplate();
   }

}
